import { getEnvVar } from '../utils/env'
import { AI_API, REQUEST_TIMEOUT } from '../constants/api'
import { handleError, ERROR_TYPES } from '../utils/errorHandler'

// AI模型配置
const AI_MODELS = {
  OPENAI: {
    name: 'ChatGPT',
    apiUrl: AI_API.OPENAI,
    getApiKey: () => getEnvVar('VITE_OPENAI_API_KEY'),
    defaultModel: 'gpt-3.5-turbo'
  },
  DEEPSEEK: {
    name: 'DeepSeek',
    apiUrl: AI_API.DEEPSEEK,
    getApiKey: () => getEnvVar('VITE_DEEPSEEK_API_KEY'),
    defaultModel: 'deepseek-chat'
  }
}

// 构建请求头
const buildHeaders = (apiKey) => ({
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${apiKey}`
})

// 格式化请求数据
const formatRequest = (model, message) => ({
  model,
  messages: [{ role: 'user', content: message }],
  temperature: 0.7,
  stream: true
})

export const getAvailableModels = () => {
  return Object.keys(AI_MODELS).map(key => ({
    id: key.toLowerCase(),
    name: AI_MODELS[key].name
  }));
};

export const sendMessageToAI = async (modelId, message, onChunk) => {
  try {
    const modelKey = modelId.toUpperCase();
    const model = AI_MODELS[modelKey];
    
    if (!model) {
       throw new Error('模型不存在');
     }

     const apiKey = model.getApiKey();
     if (!apiKey) {
       throw new Error('API密钥未配置');
     }

     const controller = new AbortController();
     const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT.AI_CHAT);

    const response = await fetch(model.apiUrl, {
      method: 'POST',
      headers: buildHeaders(apiKey),
      body: JSON.stringify(formatRequest(model.defaultModel, message)),
      signal: controller.signal
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
       const error = await response.json().catch(() => ({}));
       throw new Error(error.error?.message || '请求失败');
     }

     // 处理流式响应
     if (!response.body) {
       throw new Error('浏览器不支持流式响应');
     }

    const completeResponse = await processStreamResponse(response.body, onChunk);

    return {
      success: true,
      message: completeResponse || '回复为空'
    };
  } catch (error) {
    console.error('AI API调用失败:', error);
    
    if (error.name === 'AbortError') {
      return {
        success: false,
        message: '请求超时，请稍后再试'
      };
    }
    
    return {
      success: false,
      message: error.message || '抱歉，AI服务暂时不可用，请稍后再试。'
    };
  }
};

// 处理流式响应
const processStreamResponse = async (body, onChunk) => {
  const reader = body.getReader();
  const decoder = new TextDecoder('utf-8');
  let completeResponse = '';

  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      
      const chunk = decoder.decode(value, { stream: true });
      const lines = chunk.split('\n\n').filter(line => line.trim() !== '');
      
      for (const line of lines) {
        if (line.startsWith('data: ') && line !== 'data: [DONE]') {
          try {
            const data = JSON.parse(line.slice(6));
            const content = data.choices[0]?.delta?.content || '';
            if (content) {
              completeResponse += content;
              onChunk?.(content, completeResponse);
            }
          } catch (e) {
            console.warn('解析流式响应片段失败:', e);
          }
        }
      }
    }
  } finally {
    reader.releaseLock();
  }

  return completeResponse;
};